import java.io.*;
import java.util.ArrayList;


public class World
{
	protected int size, width, height, hour, minute, timervar, defXSpawn,defYSpawn;//w,h in blocks
	protected Blocks[][] foreground;
	protected Walls[][] background;
	protected boolean[][] wiring;
	protected String worldName;
	protected ArrayList<LivingEntity> alive=new ArrayList<LivingEntity>();
	protected Player controlled;
	protected ArrayList<PlacedEntity> itemsInWorld = new ArrayList<PlacedEntity>();//incl. furniture, all placed objects not blocks, forge, anvil, etc, and switches, levers, etc.
	public World(int x, int y, int size)
	{
		foreground = new Blocks[x][y];
		for(int i=0;i<x;i++){ for(int j=0;j<y;j++){foreground[i][j] = new Blocks(Blocks.EMPTY);}}
		background = new Walls[x][y];
		for(int i=0;i<x;i++){ for(int j=0;j<y;j++){background[i][j] = new Walls(Walls.EMPTY);}}
		wiring = new boolean[x][y];
		this.size = size;
		width = x;
		height = y;
		hour = 6;
		minute = 0;
		timervar = 0;
	}
	public World clone()
	{
		return (World)this.clone();
	}
	public boolean fgTransmuteTo(int x, int y, int type)
	{
		try
		{
			foreground[x][y].type = type;
			return true;
		}
		catch(Exception e)
		{
			return false;
		}
	}
	public void addWater(int x, int y, double z)
	{
		foreground[x][y].addWater(z);
	}
	protected void cycle()
	{
		for(int i = 0; i<alive.size();i++)
		{
			LivingEntity a= alive.get(i);
			a.move();
			a.resistance();
		}
	}
	protected void save()
	{
		try
		{
			int i = 0;
			File f = new File(worldName+".khan");
			while (f.exists())
			{
				f = new File(worldName+i+".khan");
				i++;
			}
			FileWriter fW =new FileWriter(f.getName(), true);
			fW.write(""+size+"\n");//write in size
			//write in fg, bg, wire info
			int counter = 0;
			for(i = 0; i<this.width;i++)
			{
				for(int j = 0; j<this.height;j++)
				{
					int b = (wiring[i][j]?1:0);
					fW.write(" "+foreground[i][j].type+"/"+background[i][j].type+"/"+b);
				}
				fW.write("\n");
				counter = (counter+1) %100;
				if (counter == 0)
				{
					float percent = 100*(i+1)/(width);
					System.out.printf("%2.2f%%\n", percent);
				}
			}
			//write in time
			fW.write(""+hour+" "+minute);
			//write in placed entities(when/if they are implemented)
			fW.close();
			System.out.println("Done saving");
		}
		catch(Exception e)
		{
			System.out.println("Error");
			e.printStackTrace();
		}
	}
	protected void load(String filename)
	{
		while(filename.lastIndexOf(".khan")!=-1)
		{
			filename = filename.substring(0,filename.lastIndexOf(".khan"));
		}
		
	}
/*	static World load(File f)
	{
		World w = WorldGen.makeWorld(0);
		return w;
	}*/
}
